package com.taylor.community.controller;

import com.taylor.community.entity.Event;
import com.taylor.community.event.EventProducer;
import com.taylor.community.util.CommunityConstant;
import com.taylor.community.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Controller
public class ShareController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);
    @Autowired
    private EventProducer eventProducer;
    @Value("${community.path.domain}")//域名
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Value("${wk.image.storage}")//获取配置文件里面的属性
    private String wkImageStorage;
    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;
    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;
    //生成逻辑封装成事件 交给Kafka 异步响应
    @RequestMapping(path = "/share",method = RequestMethod.GET)
    @ResponseBody
    public String share(String htmlUrl){
        //随机文件名
        String fileName = CommunityUtil.generateUUID();
        //异步方式处理生成长图
        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("htmlUrl",htmlUrl)
                .setData("fileName",fileName)
                .setData("suffix",".png");
        eventProducer.fireEvent(event);
        Map<String,Object> map = new HashMap<>();
        //返回生成图片的访问路径
//        map.put("shareUrl",domain + contextPath + "/share/image/" + fileName);
        map.put("shareUrl",shareBucketUrl +"/" + fileName);
        return CommunityUtil.getJSONString(200,"生成图片成功！",map);
    }
    //废弃
    /**
     * 从本地获取wk生成的长图
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/share/image/{fileName}",method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName")String fileName, HttpServletResponse response){
        //利用HttpServletResponse向外输出内容
        if(StringUtils.isBlank(fileName)){
            throw new IllegalArgumentException("文件名不能为空！");
        }
        //image表示输出的是图片 png表示格式
        response.setContentType("image/png");
        File file = new File(wkImageStorage + "/"+fileName + ".png");

        try {
            //用response获取输出流
            OutputStream os = response.getOutputStream();
            //将文件转化为输入流
            FileInputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];//将输入流中读到的数据放到buffer里
            int b= 0;
            //每次读取返回读取字节的长度 没有可读字节时返回-1
            while((b = inputStream.read(buffer)) != -1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("获取长图失败："+e.getMessage());
        }

    }

}
